﻿B4J=true
Group=Default Group\数据库帮助类
ModulesStructureVersion=1
Type=Class
Version=10.3
@EndOfDesignText@
'' 模块全局变量
Sub Class_Globals
	Private driverClass As String = "org.postgresql.Driver" ''驱动器
	Private host As String = "192.168.31.168" '' IP地址
	Private port As Int=25432 ''端口
	Private dataBase As String="db_test" ''数据库
	Private userName As String="postgres" '' 用户名
	Private password As String="nas!@#postgresql#@!" ''密码
	Private pgsql As SQL
End Sub

'' 初始化配置数据库配置
Public Sub Initialize
	Dim pgUrl As String=$"jdbc:postgresql://${host}:${port}/${dataBase}?ssl=false"$
	pgsql.Initialize2(driverClass,pgUrl,userName,password)
	If pgsql.IsInitialized Then
		LogHelper.WirteLog("PostgreSQL 初始化成功！")
		Try
			Dim rs As ResultSet
			rs = pgsql.ExecQuery("SELECT CURRENT_DATE")
			If rs.NextRow Then
				LogHelper.WirteLog("当前PostgreSQL数据库时间：" & rs.GetString2(0))
			End If
		Catch
			LogHelper.WirteErrorLog("PostgreSQL链接异常:" & LastException.Message)
		End Try
	End If
End Sub


' 关闭数据库连接
Public Sub Close
	If pgsql.IsInitialized Then
		pgsql.Close
		LogHelper.WirteLog("PostgreSQL连接已关闭")
	End If
End Sub

' 执行查询并返回一条结果
Public Sub ExecQuerySingleResult(sql As String,params() As Object) As String
	If Not(pgsql.IsInitialized) Then Return Null
	Try
		Return pgsql.ExecQuerySingleResult2(sql,params)
	Catch
		LogHelper.WirteErrorLog("执行查询异常: " & LastException.Message & " SQL: " & sql)
		Return Null
	End Try
End Sub

' 执行查询并返回结果集
Public Sub ExecuteQueryByList(sql As String,params() As Object) As List
	If Not(pgsql.IsInitialized) Then Return Null
	Try
		Dim rs As ResultSet= pgsql.ExecQuery2(sql,params)
		''---------
		Dim lst As List
		lst.Initialize
		''---------
		Do While rs.NextRow
			Dim mp As Map
			mp.Initialize
			Dim colCt As Int=rs.ColumnCount
			''--------
			Dim i As Int
			For i =0 To colCt-1
				Dim key As String=rs.GetColumnName(i)
				Dim value As String=rs.GetString(key)
				mp.Put(key,value)
			Next
			''--------
			lst.Add(mp)
		Loop
		''--------
		Return lst
	Catch
		LogHelper.WirteErrorLog("执行查询异常: " & LastException.Message & " SQL: " & sql)
		Return Null
	End Try
End Sub

' 执行带参数的查询（防止SQL注入）
Public Sub ExecuteQuery(sql As String, params() As Object) As ResultSet
	If Not(pgsql.IsInitialized) Then Return Null
	Try
		Return pgsql.ExecQuery2(sql, params)
	Catch
		LogHelper.WirteErrorLog("执行参数化查询异常: " & LastException.Message & " SQL: " & sql)
		Return Null
	End Try
End Sub

' 执行带参数的更新操作（防止SQL注入）
Public Sub ExecuteUpdate(sql As String, params() As Object) As Boolean
	If Not(pgsql.IsInitialized) Then Return False
	Try
		pgsql.ExecNonQuery2(sql, params)
		Return True
	Catch
		LogHelper.WirteErrorLog("执行参数化更新异常: " & LastException.Message & " SQL: " & sql)
		Return False
	End Try
End Sub

